import React, { useState, useEffect } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import './SearchPage.css';

function SearchPage() {
    const location = useLocation();
    const navigate = useNavigate();
    const [searchQuery, setSearchQuery] = useState('');
    const [searchResults, setSearchResults] = useState([]);
    const [isLoading, setIsLoading] = useState(false);
    const [error, setError] = useState(null);

    const getAuthHeaders = () => {
        const token = localStorage.getItem('token');
        return {
            'Authorization': token ? `Bearer ${token}` : '',
            'Content-Type': 'application/json'
        };
    };

    const performSearch = async (query) => {
        // if (!query.trim()) return;

        setIsLoading(true);
        setError(null);
        try {
            const response = await fetch(`/torrent/findTorrentList?q=${encodeURIComponent(query)}`, {
                headers: getAuthHeaders()
            });

            if (!response.ok) {
                throw new Error('搜索失败');
            }

            const data = await response.json();
            if (Array.isArray(data)) {
                setSearchResults(data);
            } else {
                throw new Error('无效的响应格式');
            }
        } catch (err) {
            console.error('搜索错误:', err);
            setError(err.message);
        } finally {
            setIsLoading(false);
        }
    };

    // const handleSearch = (e) => {
    //     e.preventDefault();
    //     performSearch(searchQuery);
    // };

    const handleDownloadClick = (torrentId) => {
        const token = localStorage.getItem('token');
        const userId = localStorage.getItem('userId');

        if (!token || !userId) {
            navigate('/login', { state: { from: location.pathname } });
            return;
        }

        navigate(`/download?torrent_id=${torrentId}`);
    };

    useEffect(() => {
        const queryParams = new URLSearchParams(location.search);
        const query = queryParams.get('q') || '';
        // if (query) {

            setSearchQuery(query);
            performSearch(query);
        // }
    }, [location.search]);

    return (
        <div className="search-page">
            <div className="search-container">
                {/*<div className="search-header">*/}
                {/*    <h1>种子搜索</h1>*/}
                {/*    <form onSubmit={handleSearch} className="search-form">*/}
                {/*        <input*/}
                {/*            type="text"*/}
                {/*            value={searchQuery}*/}
                {/*            onChange={(e) => setSearchQuery(e.target.value)}*/}
                {/*            placeholder="输入种子名称或描述..."*/}
                {/*            className="search-input"*/}
                {/*        />*/}
                {/*        <button type="submit" className="search-button" disabled={isLoading}>*/}
                {/*            {isLoading ? '搜索中...' : '搜索'}*/}
                {/*        </button>*/}
                {/*    </form>*/}
                {/*</div>*/}

                {error && <div className="error-message">{error}</div>}

                <div className="results-container">
                    {searchResults.length > 0 ? (
                        <div className="results-grid">
                            {searchResults.map((torrent) => (
                                <div key={torrent.torrentId} className="torrent-card">
                                    <div className="torrent-cover">
                                        <img
                                            src={`http://localhost:8080/torrent/getCoverImage?torrentId=${torrent.torrentId}`}
                                            alt={torrent.title}
                                            // onError={(e) => {
                                            //     e.target.src = '/placeholder-cover.png';
                                            // }}
                                        />
                                    </div>
                                    <div className="torrent-info">
                                        <h3 className="torrent-title">{torrent.title}</h3>
                                        <p className="torrent-description">{torrent.description}</p>
                                        <div className="torrent-meta">
                                            <span className="torrent-category">{torrent.category}</span>
                                            <span className="torrent-tags">{torrent.tags}</span>
                                            <span className="torrent-time">{new Date(torrent.uploadTime).toLocaleString()}</span>
                                        </div>
                                        <button
                                            onClick={() => handleDownloadClick(torrent.torrentId)}
                                            className="download-button"
                                        >
                                            查看详情并下载
                                        </button>
                                    </div>
                                </div>
                            ))}
                        </div>
                    ) : (
                        <div className="no-results">
                            {isLoading ? (
                                <p>正在加载...</p>
                            ) : (
                                searchQuery ? <p>没有找到匹配的种子</p> : <p>请输入搜索内容</p>
                            )}
                        </div>
                    )}
                </div>
            </div>
        </div>
    );
}

export default SearchPage;
